<?php
class Downloader extends Podcast {

	public function showContent() {

		// clear tag
		self::$podcast = str_replace("+-+player", "", self::$podcast);

		// save as loaded episode
		$query = "INSERT INTO `pp_loaded_episodes` (`filename` , `podcast_tag`) VALUES ('".self::$episode."', '".self::$podcast."');";
		self::$db->query($query);

		$filepath = $this->getFilepath();
		$filesize = filesize($filepath);

		if (file_exists($filepath)) {
			// if file is too big, increase ini memory limit
			$ini_limit = substr(ini_get("memory_limit"), 0, -1);
			$ini_limit = $ini_limit * 1024 * 1024;
			if($filesize > $ini_limit) {
				ini_set("memory_limit", "256M");
			}

			header('Content-Description: File Transfer');
			header('Content-Type: application/octet-stream');
			header('Content-Disposition: attachment; filename='.basename($filepath));
			header('Content-Transfer-Encoding: binary');
			header('Expires: 0');
			header('Cache-Control: must-revalidate');
			header('Pragma: public');
			header('Content-Length: ' . filesize($filepath));
			ob_clean();
			flush();
			readfile($filepath);
			exit;
		}
	}

	private function getFilepath() {
		$res = "";

		$arr = explode(".", self::$episode);
		$format = ".".array_pop($arr);
		$filename = implode(".", $arr);

		// at first search for file with same filename and format
		foreach (self::$files as $cachedFile) {
			if($filename.$format == $cachedFile["filename"].$cachedFile["extension"]) {
				$res = $cachedFile["filepath"];
				break;
			}
		}

		// if there is no result, just search for file with same filename
		if($res == "") {
			foreach (self::$files as $cachedFile) {
				if($filename == $cachedFile["filename"]) {
					$res = $cachedFile["filepath"];
					break;
				}
			}
		}

		return $res;
	}
}

?>
